package cn.ac.iie.di.wx.handler;

import cn.ac.iie.di.commons.httpserver.framework.handler.HandlerI;
import cn.ac.iie.di.commons.httpserver.framework.util.ParseRequestStream;
import cn.ac.iie.di.wx.common.RuntimeEnv;
import cn.ac.iie.di.wx.httpservice.HttpSender;
import cn.ac.iie.di.wx.utils.GenerateMD5Util;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.log4j.Logger;
import org.eclipse.jetty.server.Request;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author Administrator
 */
public class WxPictureUrl_cache_yizhuang implements HandlerI {

    static Logger logger = Logger.getLogger(WxPictureUrl_cache_yizhuang.class.getName());

    @Override
    public void init() throws Exception {
    }

    @Override
    public void execute(Request pRequest, HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {

            String _idurlStr = ParseRequestStream.parseRequestStreamAsString(pRequest.getInputStream());
            logger.info(_idurlStr);
            byte[] bytesContent = new byte[1024 * 2];
            int bytesReadIn = 0;
            ServletOutputStream out = response.getOutputStream();
            BufferedOutputStream bos = new BufferedOutputStream(out);
            JSONObject urljSON = JSONObject.parseObject(_idurlStr);
            String url = urljSON.getString("url");
            String download_url_MD5 = GenerateMD5Util.string2MD5(url) + ".jpg";
            File file = new File((String) RuntimeEnv.getParam(RuntimeEnv.PICCACHE) + download_url_MD5);
            logger.info((String) RuntimeEnv.getParam(RuntimeEnv.PICCACHE) + download_url_MD5);
            if (file.exists() && ((String) RuntimeEnv.getParam(RuntimeEnv.cacheFlag)).equals("true")) {
                try {

                    //龙存已经存在该图片，读取文件进行返回
                    logger.info("read from file");
                    InputStream responseIn = new FileInputStream(file);
                    if (responseIn.available() == 0) {

                        logger.info("this file is empty," + "removing is " + file.delete());
                        responseIn = new ByteArrayInputStream(("腾讯图片接口调用失败：" + "图片大小为零").getBytes("UTF-8"));
                    }
                    BufferedInputStream bis = new BufferedInputStream(responseIn);
                    while ((bytesReadIn = bis.read(bytesContent, 0, 1024 * 2)) > 0) {
                        bos.write(bytesContent, 0, bytesReadIn);
                    }
                    bos.flush();
                    bos.close();
                    bis.close();
                } catch (IOException e) {
                    logger.error("加载本地图片出错" + e.getMessage(), e);
                }
            } else {
                //龙存没有该图片，进行下载，并将图片写入 龙存
                HttpPost httppost = null;
                InputStream inputStream = null;
                HttpClient httpClient = new DefaultHttpClient();
                try {

                    logger.info("downlad from server");
                    file.createNewFile();
                    FileOutputStream outputStream = new FileOutputStream(file);
                    BufferedOutputStream fileOut = new BufferedOutputStream(outputStream);
//                InputStream responseIn = org.apache.http.client.fluent.Request.Get(download_url.replace("10.177.138.34", "10.238.3.12"))
//                        .execute().returnContent().asStream();
                    //从数北下载
//                    HttpSender hs = new HttpSender();
                    logger.info("request is " + _idurlStr + "====to http post = " + (String) RuntimeEnv.getParam(RuntimeEnv.wxPicQueryUrl));
//                    InputStream responseIn = hs.picInputStream(_idurlStr, (String) RuntimeEnv.getParam(RuntimeEnv.wxPicQueryUrl));

                    logger.info(_idurlStr + "======>>" + (String) RuntimeEnv.getParam(RuntimeEnv.wxPicQueryUrl));
                    //默认字符编码是ISO-8859-1
                    httppost = new HttpPost((String) RuntimeEnv.getParam(RuntimeEnv.wxPicQueryUrl));
                    InputStreamEntity reqEntity = new InputStreamEntity(new ByteArrayInputStream(_idurlStr.getBytes("UTF-8")), -1);
                    reqEntity.setContentType("application/octet-stream");// 区分不同种类的数据,xml数据
                    reqEntity.setContentEncoding("UTF-8");// charset=UTF-8
                    httppost.setEntity(reqEntity);
                    logger.info("开始发送");
                    HttpResponse picresponse = httpClient.execute(httppost);
                    StatusLine sl = picresponse.getStatusLine();
                    if (sl.getStatusCode() == 200) {
                        inputStream = picresponse.getEntity().getContent();
                        logger.info("200" + inputStream.available());
                    } else {
                        inputStream = picresponse.getEntity().getContent();
                        logger.info("下载完成" + inputStream.available());
                    }
                    while ((bytesReadIn = inputStream.read(bytesContent, 0, 1024 * 2)) > 0) {
                        bos.write(bytesContent, 0, bytesReadIn);
                        fileOut.write(bytesContent, 0, bytesReadIn);
                    }
                    fileOut.flush();
                    bos.flush();
                    fileOut.close();
                    outputStream.close();
                    bos.close();
                } catch (IOException e) {
                    logger.error("下载图片出错" + e.getMessage(), e);
                } finally {
                    httppost.releaseConnection();
                    httpClient.getConnectionManager().shutdown();
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

}
